package com.baidu.foody.ui.fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.baidu.foody.R
import com.baidu.foody.adapter.RecipeAdapter
import com.baidu.foody.bindingadapter.ClickEvents
import com.baidu.foody.databinding.FragmentRecipeBinding
import com.baidu.foody.util.NetworkResult
import com.baidu.foody.viewmodel.MainViewModel


class RecipeFragment : Fragment() {
    private val mMainViewModel: MainViewModel by activityViewModels()
    private lateinit var mBinding: FragmentRecipeBinding
    private val mAdapter = RecipeAdapter()
    private val args: RecipeFragmentArgs by navArgs()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = FragmentRecipeBinding.inflate(inflater, container, false)
        initView()
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (args.shouldRefresh){
            Toast.makeText(requireContext(),"refresh: ${args.mealType}", Toast.LENGTH_SHORT).show()
            mMainViewModel.loadFoodRecipes("cherry",args.dietType,args.mealType)
        }else{
            Toast.makeText(requireContext(),"default", Toast.LENGTH_SHORT).show()
            mMainViewModel.loadFoodRecipes()
        }
    }

    private fun initView(){
        //配置xml中绑定的数据
        mBinding.viewModel = mMainViewModel
        mBinding.clickEvents = ClickEvents()
        mBinding.lifecycleOwner = this
        mBinding.executePendingBindings()

        mBinding.recyclerView.initAdapter(mAdapter)

        //需要刷新界面

        mMainViewModel.networkResult.observe(viewLifecycleOwner){ result ->
            when(result){
                is NetworkResult.Loading ->{
                    //显示加载动画
                    mBinding.recyclerView.showShimmer()
                }
                is NetworkResult.Success ->{
                    //加载数据成功
                    mAdapter.setRecipes(result.data.results)
                    mBinding.recyclerView.hideShimmer()
                }
                is NetworkResult.Failure ->{
                    Toast.makeText(requireContext(),"${result.message}",Toast.LENGTH_SHORT).show()
                    mBinding.recyclerView.hideShimmer()
                }
            }
        }
    }
}